﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MsgCenter.DAL.Base;
using Utility.Model;
using Utility;
using Hxj.Data;
using Utility.Json;
using System.Data;
using Utility.Comm;
using Utility.Config;

namespace MsgCenter.BLL.Impl
{
    public class BLL_Write
    {
        private readonly BaseService dal = new BaseService();

        public void Save(List<TB_SMS_Message> listMessage)
        {
            DbTrans trans = dal.GetDataBase().BeginTransaction();
            try
            {
                int index = 0;
                foreach (TB_SMS_Message message in listMessage)
                {
                    message.SendDate = message.SendDate.ToSafeDateTime().AddMilliseconds(1);
                    dal.Save<TB_SMS_Message>(message, trans);
                    index = index + 1;
                }
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                throw ex;
            }
            finally
            {
                trans.Close();
            }

        }
        public void Save(TB_SMS_Message message)
        {
            DbTrans trans = dal.GetDataBase().BeginTransaction();
            try
            {
                dal.Save<TB_SMS_Message>(message, trans);
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                throw ex;
            }
            finally
            {
                trans.Close();
            }
        }

        public JsonRetData WS_CancelMessge(string strMessageID, string strApplicationCode)
        {
            JsonRetData json = new JsonRetData();
            try
            {
                Sys_AppReg model = dal.GetModel<Sys_AppReg>(Sys_AppReg._.AppCode == strApplicationCode && Sys_AppReg._.IsDelete == false);
                if (model == null)
                {
                    json.State = "false";
                    json.Message = "撤销失败：系统编码还没有进行注册";
                }
                else
                {
                    dal.ExecuteNonQuery("Update TB_SMS_Message set Status=-1 where BussinessID='" + strMessageID + "'");
                    json.State = "true";
                }
            }
            catch (Exception ex)
            {
                json.State = "false";
                json.Message = "撤销失败：" + ex.Message;
            }
            return json;
        }

        public JsonRetData WS_SetReadMessage(string strMessageID, string strApplicationCode)
        {
            JsonRetData json = new JsonRetData();
            try
            {
                Sys_AppReg model = dal.GetModel<Sys_AppReg>(Sys_AppReg._.AppCode == strApplicationCode && Sys_AppReg._.IsDelete == false);
                if (model == null)
                {
                    json.State = "false";
                    json.Message = "设置失败：系统编码还没有进行注册";
                }
                else
                {
                    dal.ExecuteNonQuery("Update TB_SMS_Message set IsRead=1,Status=1 where BussinessID='" + strMessageID + "'");
                    json.State = "true";
                }
            }
            catch (Exception ex)
            {
                json.State = "false";
                json.Message = "设置失败：" + ex.Message;
            }
            return json;
        }

        public PagerCondition WS_QueryReceive(string strReceiveLoginName, string strApplicationCode, string strSendType,
            string strSendStartDate, string strSendEndDate, int pageIndex, int pageSize, string strOrderField, string strDescOrAsc)
        {
            WhereClip wcp = new WhereClip();
            wcp = wcp.And(TB_SMS_Message._.ReceiveLoginName == strReceiveLoginName);
            wcp = wcp.And(TB_SMS_Message._.SystemCode == strApplicationCode);
            if (!strSendType.IsNullOrEmpty())
            {
                wcp = wcp.And(TB_SMS_Message._.SendType == strSendType);
            }
            if (!strSendStartDate.IsNullOrEmpty() && strSendStartDate.IsDateTime())
            {
                wcp = wcp.And(TB_SMS_Message._.SendDate >= strSendStartDate.ToSafeDateTime());
            }
            if (!strSendEndDate.IsNullOrEmpty() && strSendEndDate.IsDateTime())
            {
                wcp = wcp.And(TB_SMS_Message._.SendDate <= strSendEndDate.ToSafeDateTime());
            }
            OrderByClip order = null;

            PagerCondition pager = new PagerCondition();
            if (!strOrderField.IsNullOrEmpty())
            {
                pager.SortExpression = strOrderField;
            }
            else
            {
                pager.SortExpression = "SendDate";
            }
            if (!strDescOrAsc.IsNullOrEmpty())
            {
                pager.SortDirection = strDescOrAsc;
            }
            else
            {
                pager.SortDirection = "desc";
            }
            if (pager.SortDirection.ToEquals("desc"))
            {
                order = new OrderByClip(pager.SortExpression, OrderByOperater.DESC);
            }
            else
            {
                order = new OrderByClip(pager.SortExpression, OrderByOperater.ASC);
            }
            pager.CurrentPage = pageIndex.ToSafeInt();
            pager.PageSize = pageSize.ToSafeInt();
            pager.ComplexSearchCondition = wcp;
            pager.OrderBy = order;
            pager.DataJson = dal.GetTable<TB_SMS_Message>(pager).ToJson();
            return pager;
        }

        public PagerCondition WS_QuerySend(string strSendLoginName, string strApplicationCode, string strSendType,
            string strSendStartDate, string strSendEndDate, int pageIndex, int pageSize, string strOrderField, string strDescOrAsc)
        {
            WhereClip wcp = new WhereClip();
            wcp = wcp.And(TB_SMS_Message._.SendLoginName == strSendLoginName);
            wcp = wcp.And(TB_SMS_Message._.SystemCode == strApplicationCode);
            if (!strSendType.IsNullOrEmpty())
            {
                wcp = wcp.And(TB_SMS_Message._.SendType == strSendType);
            }
            if (!strSendStartDate.IsNullOrEmpty() && strSendStartDate.IsDateTime())
            {
                wcp = wcp.And(TB_SMS_Message._.SendDate >= strSendStartDate.ToSafeDateTime());
            }
            if (!strSendEndDate.IsNullOrEmpty() && strSendEndDate.IsDateTime())
            {
                wcp = wcp.And(TB_SMS_Message._.SendDate <= strSendEndDate.ToSafeDateTime());
            }
            PagerCondition pager = new PagerCondition();
            OrderByClip order = null;
            if (!strOrderField.IsNullOrEmpty())
            {
                pager.SortExpression = strOrderField;
            }
            else
            {
                pager.SortExpression = "SendDate";
            }
            if (!strDescOrAsc.IsNullOrEmpty())
            {
                pager.SortDirection = strDescOrAsc;
            }
            else
            {
                pager.SortDirection = "desc";
            }
            if (pager.SortDirection.ToEquals("desc"))
            {
                order = new OrderByClip(pager.SortExpression, OrderByOperater.DESC);
            }
            else
            {
                order = new OrderByClip(pager.SortExpression, OrderByOperater.ASC);
            }
            pager.CurrentPage = pageIndex.ToSafeInt();
            pager.PageSize = pageSize.ToSafeInt();
            pager.ComplexSearchCondition = wcp;
            pager.OrderBy = order;
            pager.DataJson = dal.GetTable<TB_SMS_Message>(pager).ToJson();
            return pager;
        }

        private JsonRetData GetAppReg(string strApplicationCode, ref Sys_AppReg model)
        {
            JsonRetData json = null;
            Sys_AppReg modelNew = dal.GetModel<Sys_AppReg>(Sys_AppReg._.AppCode == strApplicationCode && Sys_AppReg._.IsDelete == false);
            model = modelNew;
            if (modelNew == null)
            {
                json = new JsonRetData();
                json.State = "false";
                json.Message = "发送失败：系统编码还没有进行注册";
            }
            return json;
        }

        private JsonRetData GetTemplet(string strTempletNo, ref Sys_Templet modelTemp)
        {
            JsonRetData json = null;
            Sys_Templet modelTempNew = dal.GetModel<Sys_Templet>(Sys_Templet._.TempAppCode == strTempletNo && Sys_Templet._.IsDelete == false);
            modelTemp = modelTempNew;
            if (modelTempNew == null)
            {
                json = new JsonRetData();
                json.State = "false";
                json.Message = "发送失败：模板编号还没有进行注册";
            }
            return json;
        }

        private JsonRetData GetRoleName(string strRoleName, ref Sys_Role modelTemp)
        {
            JsonRetData json = null;
            Sys_Role modelTempNew = dal.GetModel<Sys_Role>(Sys_Role._.RoleName == strRoleName && Sys_Role._.IsDelete == false);
            modelTemp = modelTempNew;
            if (modelTempNew == null)
            {
                json = new JsonRetData();
                json.State = "false";
                json.Message = "发送失败：角色名称还没进行设置";
            }
            return json;
        }

        private JsonRetData AllowClientIP(string strSendIP)
        {
            JsonRetData json = null;
            List<string> list = ConfigHelper.strAllowClientIP.Split(',').ToList();
            if (!list.Contains(strSendIP))
            {
                json = new JsonRetData();
                json.State = "false";
                json.Message = "发送失败：该发送IP(" + strSendIP + ")存在异常，请联系管理员";
            }
            return json;
        }
        public JsonRetData WS_SendMessge(string strMessageID, string strApplicationCode, string strTempletNo, string[] strMessage, string strReceiveLoginName, string strSendIP)
        {
            JsonRetData jsonRetData = null;
            try
            {
                Sys_AppReg model = null;
                Sys_Templet modelTemp = null;
                jsonRetData = AllowClientIP(strSendIP);
                if (jsonRetData == null)
                {
                    jsonRetData = GetAppReg(strApplicationCode, ref model);
                    if (jsonRetData == null)
                    {
                        jsonRetData = GetTemplet(strTempletNo, ref modelTemp);
                        if (jsonRetData == null)
                        {
                            jsonRetData = new JsonRetData();

                            TB_SMS_Message tB_SMS_Message = getMessage(model, modelTemp, strMessageID, strApplicationCode, strTempletNo, strMessage, "", strSendIP);
                            if (tB_SMS_Message != null)
                            {
                                Sys_User model2 = dal.GetModel<Sys_User>(Sys_User._.UserName == strReceiveLoginName);
                                if (model2 != null)
                                {
                                    tB_SMS_Message.WebChat = model2.WebChat;
                                    tB_SMS_Message.Mobile1 = model2.Mobile;
                                    tB_SMS_Message.Mobile2 = model2.Mobile;
                                    tB_SMS_Message.QQ = model2.QQ;
                                    tB_SMS_Message.ReceiveUserName = model2.Name;
                                    tB_SMS_Message.RtxLoginName = model2.RtxLoginName;
                                }
                            }
                            else
                            {
                                throw new Exception("您的参数值与系统配置模板参数不匹配，请核对！");
                            }
                            dal.Save(tB_SMS_Message);
                            jsonRetData.State = "true";
                            return jsonRetData;
                        }
                        return jsonRetData;
                    }
                    return jsonRetData;
                }
                return jsonRetData;
            }
            catch (Exception ex)
            {
                Utility.Log.LogHelper.WriteError("发送失败（WS_SendMessge）" + ex.Message);
                jsonRetData = new JsonRetData();
                jsonRetData.State = "false";
                jsonRetData.Message = "发送失败：" + ex.Message;
                return jsonRetData;
            }
        }

        private TB_SMS_Message getMessage(Sys_AppReg model, Sys_Templet modelTemp, string strMessageID, string strApplicationCode, string strTempletNo, string[] strMessage, string strMobile, string strSendIP)
        {
            string text = modelTemp.TempletDes;
            string text2 = string.Empty;
            for (int i = 0; i < strMessage.Length; i++)
            {
                text = text.Replace("{" + i.ToIntString() + "}", strMessage[i]);
                if (text2.IsNullOrEmpty())
                {
                    text2 = strMessage[i].ToReplace("|", "");
                }
                else
                {
                    text2 = text2 + "|" + strMessage[i].ToReplace("|", "");
                }
            }
            if (text.Contains("{"))
            {
                throw new Exception("您的参数值与系统配置模板参数不匹配，请核对！");
            }
            TB_SMS_Message tB_SMS_Message = new TB_SMS_Message();
            tB_SMS_Message.BussinessID = strMessageID;
            tB_SMS_Message.IsInstant = 1;
            tB_SMS_Message.IsRead = 0;
            tB_SMS_Message.Messge = text;
            tB_SMS_Message.ReceiveLoginName = strMobile;
            tB_SMS_Message.SendLoginName = model.AppCode;
            tB_SMS_Message.SendUserName = model.AppName;
            tB_SMS_Message.SendDate = DateTime.Now;
            tB_SMS_Message.SendIP = strSendIP;
            tB_SMS_Message.SendType = "短信";
            tB_SMS_Message.SiteLoginName = strMobile;
            tB_SMS_Message.SystemCode = strApplicationCode;
            tB_SMS_Message.Mobile1 = strMobile;
            tB_SMS_Message.Mobile2 = strMobile;
            tB_SMS_Message.AliTempletCode = modelTemp.AliTempletCode;
            tB_SMS_Message.SendTempletMsg = text2;
            return tB_SMS_Message;
        }

        public JsonRetData WS_SendMessge_Mobile(string strMessageID, string strApplicationCode, string strTempletNo, string[] strMessage, string strMobile, string strSendIP)
        {
            JsonRetData jsonRetData = null;
            try
            {
                Sys_AppReg model = null;
                Sys_Templet modelTemp = null;
                jsonRetData = AllowClientIP(strSendIP);
                if (jsonRetData == null)
                {
                    jsonRetData = GetAppReg(strApplicationCode, ref model);
                    if (jsonRetData == null)
                    {
                        jsonRetData = GetTemplet(strTempletNo, ref modelTemp);
                        if (jsonRetData == null)
                        {
                            jsonRetData = new JsonRetData();

                            TB_SMS_Message tbSms = getMessage(model, modelTemp, strMessageID, strApplicationCode, strTempletNo, strMessage, strMobile, strSendIP);

                            dal.Save(tbSms);
                            jsonRetData.State = "true";
                            return jsonRetData;
                        }
                        return jsonRetData;
                    }
                    return jsonRetData;
                }
                return jsonRetData;
            }
            catch (Exception ex)
            {
                Utility.Log.LogHelper.WriteError("发送失败（WS_SendMessge_Mobile）:" + ex.Message);
                jsonRetData = new JsonRetData();
                jsonRetData.State = "false";
                jsonRetData.Message = "发送失败：" + ex.Message;
                return jsonRetData;
            }
        }

        public JsonRetData WS_SendMessge_Role(string strMessageID, string strApplicationCode, string strTempletNo, string[] strMessage, string strMobile, string strSendIP)
        {
            JsonRetData jsonRetData = null;
            try
            {
                Sys_AppReg model = null;
                Sys_Templet modelTemp = null;
                jsonRetData = AllowClientIP(strSendIP);
                if (jsonRetData == null)
                {
                    jsonRetData = GetAppReg(strApplicationCode, ref model);
                    if (jsonRetData == null)
                    {
                        jsonRetData = GetTemplet(strTempletNo, ref modelTemp);
                        if (jsonRetData == null)
                        {
                            jsonRetData = new JsonRetData();

                            TB_SMS_Message tbSms = getMessage(model, modelTemp, strMessageID, strApplicationCode, strTempletNo, strMessage, strMobile, strSendIP);

                            dal.Save(tbSms);
                            jsonRetData.State = "true";
                            return jsonRetData;
                        }
                        return jsonRetData;
                    }
                    return jsonRetData;
                }
                return jsonRetData;
            }
            catch (Exception ex)
            {
                Utility.Log.LogHelper.WriteError("发送失败(WS_SendMessge_Role):" + ex.Message);
                jsonRetData = new JsonRetData();
                jsonRetData.State = "false";
                jsonRetData.Message = "发送失败：" + ex.Message;
                return jsonRetData;
            }
        }

        public void AuditMessage(string strDataID)
        {
            if (strDataID.Length > 0)
            {
                string[] array = strDataID.Trim(',').Split(',');
                DbTrans dbTrans = dal.GetDataBase().BeginTransaction();
                try
                {
                    string[] array2 = array;
                    foreach (string str in array2)
                    {
                        dal.ExecuteNonQuery("Update TB_SMS_Message set Status=0 where SMSID='" + str + "'", dbTrans);
                    }
                    dbTrans.Commit();
                }
                catch (Exception ex)
                {
                    dbTrans.Rollback();
                    throw ex;
                }
                finally
                {
                    dbTrans.Close();
                }
            }
        }
    }
}